package com.lixin.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 多线程精准唤醒
public class Exact {

    private int num = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void taskA() {
        lock.lock();
        try {
            while (num != 1) condition1.await();
            System.out.println("A任务执行");
            num = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void taskB() {
        lock.lock();
        try {
            while (num != 2) condition2.await();
            System.out.println("B任务执行");
            num = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void taskC() {
        lock.lock();
        try {
            while (num != 3) condition3.await();
            System.out.println("C任务执行");
            num = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
